<?php
session_start();

include "config.php";

//Debug
if (!$debug)
{
    error_reporting(0);
}

//Carga de controladores de core y rutas
$array_config = array(
    "language"=>$config_language,
    "mysql_config"=>array(
        "server"=>$mysql_server,
        "username"=>$mysql_username,
        "password"=>$mysql_password,
        "database"=>$mysql_database,
        "debug"=>$die_on_error
    ),
    "debug"=>$debug,
    "html"=>array(
        "prototype"=>$prototype
    )
);
require_once "routes.php";
require_once "core/app_controller.php";
$APP = new AppController($array_config);

//Parseo la url en forma /controlador/metodo/param1/param2/param..n
if (strpos($_SERVER['REQUEST_URI'],"?") !== false)
{
    $tmp = explode('?',$_SERVER['REQUEST_URI']);

    $RequestURI = $tmp[0];

    if (strpos($tmp[1],"&") !== false)
    {
        $t = explode("&",$tmp[1]);
        foreach ($t as $param)
        {
                $tmp = explode("=",$param);
                $params[$tmp[0]]=$tmp[1];
        }
    }else{
        $t = explode("=",$tmp[1]);
        $params[$t[0]]=$t[1];
    }

}else{
    $RequestURI = $_SERVER['REQUEST_URI'];
}

$site_base_dir = str_replace('index.php','',$_SERVER['PHP_SELF']);

if ($site_base_dir == '/')
{
    $tmp = explode('/',substr($RequestURI,1,strlen($RequestURI)));
}else{
    $tmp = explode('/',str_replace($site_base_dir,'',$RequestURI));
}

$controller = $tmp[0];
$method = $tmp[1];
foreach ($tmp as $key=>$param)
{
    if ($key != 0 && $key != 1)
    {
        $params[]=$param;
    }
}

if ($controller == "" && $method == "")
{
    if (isset($ROUTES["/"]))
    {
        $controller = $ROUTES["/"]["Controller"];
        $method = $ROUTES["/"]["Method"];
    }
}


if ($controller != "" && $method != "")
{
    $isparam=false;
    if (is_numeric($method))
    {
        $key = "/" . $controller . "/(number)";
        $isparam=true;
    }else{
        $key = "/" . $controller . "/" . $method;
        if (!isset($ROUTES[$key]))
        {
            $key = "/" . $controller . "/(string)";
            $isparam=true;
        }
    }
}else if ($method == "")
{
    if (!file_exists("./controllers/{$controller}_controller.php"))
    {
        $key = "/(string)";
    }else{
        $key = "/" . $controller;
    }
}

if (isset($ROUTES[$key]))
{
    $route_data = $ROUTES[$key];
    $controller = $route_data['Controller'];
    if ($isparam)
    {
        $params[]=$method;
    }

    $method = $route_data['Method'];
}

if (file_exists("./controllers/{$controller}_controller.php"))
{
    require_once "./controllers/{$controller}_controller.php";
}else{
    header("HTTP/1.0 404 Not Found");
    die();
}
$Controller = $APP->create_user_class_array(ucwords($controller).'Controller');
$method = strtolower($method);
$Controller->$method($params);
if ( isset($Controller->Layout) )
{
    $Layout = $Controller->Layout;
}
$APP->View(strtolower($controller) . '/' . strtolower($method),$Layout);
?>